
package com.hlkj.pay.app.merchant.ext.impl.gtzfpay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessAuthQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.constant.GtzfPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.dto.GtzfPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils.GtzfPayRsaUtil;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils.HttpUtils;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigAppIdDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigListDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author HlpayTeam
 * @date 2024/10/16 9:10
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class GtzfPayMerchantAccessConfigHandler extends GtzfPayMerchantCommonParamsHandle {

    /**
     * 微信/支付宝 子商户查询
     * 
     * @param channelMerchantBusinessContext
     */
    public void processSubMerInfoQuery(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<GtzfPayConfig> gtzfPayConfigCommonResult = channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!gtzfPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(gtzfPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        GtzfPayConfig config = gtzfPayConfigCommonResult.getData();
        // 1. 数据初始化
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            CommonResult<Map<String, String>> paramsCommonResult = GtzfPayMerchantParamsHandle.getReportInfo(config, merchantAccessInfo.getSubMchId());
            Map<String, String> params = paramsCommonResult.getData();
            params.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(params), config.getMchPublicKey()));
            String url = domain(channelMerchantBusinessContext.isTest()) + GtzfPayConstant.MERCHANT_AUTH_RESULT_QUERY;
            log.info("国通商户报备信息查询请求参数:{}", JsonUtils.toJsonString(params));
            String response = HttpUtils.post(url, JsonUtils.toJsonString(params));
            log.info("国通商户报备信息查询返回参数:{}", response);
            JSONObject respObj = JsonUtils.parseObj(response);
            if (!"000000".equals(respObj.getStr("code"))) {
                channelMerchantBusinessContext.setRemark(respObj.getStr("msg"));
                log.error("国通商户报备信息查询异常 message: {}", respObj.getStr("msg"));
                return;
            }
            JSONObject dataObj = respObj.getJSONObject("data");
            JSONArray funcInfoArr = dataObj.getJSONArray("list");
            List<MerchantAccessAuthDO> merchantAccessAuthList = new ArrayList<>();
            for (int i = 0; i < funcInfoArr.size(); i++) {
                JSONObject funcInfo = funcInfoArr.getJSONObject(i);
                if (!funcInfo.containsKey("thirdMercid") || !StringUtils.hasText(funcInfo.getStr("thirdMercid"))) {
                    continue;
                }
                MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                merchantAccessAuthDO.setChannelJson(funcInfo.getStr("reMercid"));
                merchantAccessAuthDO.setAuthCode("");
                switch (funcInfo.getStr("payWay")) {
                    case "02":
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
                        merchantAccessAuthDO.setSubMchId(funcInfo.getStr("thirdMercid"));
                        merchantAccessAuthDO.setMchId(funcInfo.getStr("zfbPid"));
                        merchantAccessAuthDO.setAuthUrl(config.getAliQrcode());
                        break;
                    case "01":
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
                        merchantAccessAuthDO.setSubMchId(funcInfo.getStr("thirdMercid"));
                        merchantAccessAuthDO.setMchId(funcInfo.getStr("wxQdh"));
                        merchantAccessAuthDO.setAuthUrl(config.getWxQrcode());
                        break;
                    default:
                        continue;
                }

                switch (funcInfo.getStr("status")) {
                    case "02":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_FAIL.getCode());
                        break;
                    case "01":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                        break;
                    case "00":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                        break;
                }
                merchantAccessAuthDO.setRejectReason(funcInfo.getStr("result"));
                merchantAccessAuthList.add(merchantAccessAuthDO);
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_CONFIG);
            channelMerchantBusinessContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_SUCCESS);
        } catch (Exception e) {
            log.error("国通商户报备信息查询请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("国通商户报备信息查询请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantBusinessContext
     */
    public void processWxAuth(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<GtzfPayConfig> gtzfPayConfigCommonResult = channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!gtzfPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(gtzfPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            GtzfPayConfig gtzfPayConfig = gtzfPayConfigCommonResult.getData();
            MerchantAccessAuthDO merchantAccessAuth = channelMerchantBusinessContext.getMerchantAccessAuth();
            MerchantWechatConfigDto merchantWechatConfigDto = channelMerchantBusinessContext.getMerchantWechatConfigDto();
            CommonResult<Map<String, String>> authCommonResult = GtzfPayMerchantParamsHandle.wxConfig(channelMerchantBusinessContext, gtzfPayConfig, merchantAccessAuth);
            Map<String, String> authParams = authCommonResult.getData();
            authParams.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(authParams), gtzfPayConfig.getMchPublicKey()));

            String authUrl = domain(channelMerchantBusinessContext.isTest()) + GtzfPayConstant.MERCHANT_WX_APPID_SETTING;
            if (StringUtils.hasText(merchantWechatConfigDto.getJsAPIPath())) {
                authUrl = domain(channelMerchantBusinessContext.isTest()) + GtzfPayConstant.MERCHANT_WX_PATH_SETTING;
            }
            log.info("国通微信参数配置请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.post(authUrl, authParams);
            log.info("国通微信参数配置返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"000000".equals(authResp.getStr("code"))) {
                channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantBusinessContext.setRemark(authResp.getStr("msg"));
                log.error("国通微信参数配置异常 message: {}", authResp.getStr("msg"));
            }
        } catch (Exception e) {
            log.error("国通微信参数配置请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("国通微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信参数配置查询
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxConfigQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<GtzfPayConfig> gtzfPayConfigCommonResult = channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!gtzfPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(gtzfPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        GtzfPayConfig gtzfPayConfig = gtzfPayConfigCommonResult.getData();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthDbList();
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            // 没有微信报备 执行支付宝报备
            if (CollectionUtils.isEmpty(merchantAccessAuthList)) {
                channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
                return;
            }
            String url = domain(channelMerchantAccessAuthQueryContext.isTest()) + GtzfPayConstant.MERCHANT_WX_AUTH_CONFIG_QUERY;
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessAuthQueryContext.getMerchantAccessInfo();
            MerchantWechatConfigListDto merchantWechatConfigListDto = new MerchantWechatConfigListDto();
            List<MerchantWechatConfigAppIdDto> appIdList = new ArrayList<>();
            List<String> jsApiPath = new ArrayList<>();
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthList) {
                if (!PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())) {
                    log.info("国通微信配置查询 非报备非微信类型直接返回 type:{},subMchId:{}", merchantAccessAuthDO.getType(), merchantAccessAuthDO.getSubMchId());
                    continue;
                }
                CommonResult<Map<String, String>> paramsCommonResult = GtzfPayMerchantParamsHandle.wxConfigQuery(gtzfPayConfig, merchantAccessInfo.getSubMchId(), merchantAccessAuthDO);
                Map<String, String> params = paramsCommonResult.getData();
                params.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(params), gtzfPayConfig.getMchPublicKey()));

                log.info("国通微信配置查询请求参数:{}", JsonUtils.toJsonString(params));
                String response = HttpUtils.post(url, params);
                log.info("国通微信配置查询返回参数:{}", response);
                JSONObject respObj = JsonUtils.parseObj(response);
                if (!"000000".equals(respObj.getStr("code"))) {
                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(respObj.getStr("msg"));
                    log.error("国通微信配置查询异常 message: {}", respObj.getStr("msg"));
                }
                try {
                    if (!CollectionUtils.isEmpty(respObj.getJSONObject("data"))) {
                        JSONObject configObj = respObj.getJSONObject("data");
                        if (configObj.containsKey("appidConfigList") && StringUtils.hasText(configObj.getStr("appidConfigList"))) {
                            JSONArray arr = configObj.getJSONArray("appidConfigList");
                            if (!arr.isEmpty()) {
                                arr.stream().forEach(resp -> {
                                    JSONObject config = (JSONObject)resp;
                                    MerchantWechatConfigAppIdDto merchantWechatConfigAppIdDto = new MerchantWechatConfigAppIdDto();
                                    merchantWechatConfigAppIdDto.setSubAppid(config.getStr("sub_appid"));
                                    merchantWechatConfigAppIdDto.setSubscribeAppid(config.getStr("subscribe_appid"));
                                    appIdList.add(merchantWechatConfigAppIdDto);
                                });
                            }
                        }
                        if (configObj.containsKey("jsapiPathList") && StringUtils.hasText(configObj.getStr("jsapiPathList"))) {
                            JSONArray arr =  configObj.getJSONArray("jsapiPathList");
                            for (int i = 0; i < arr.size(); i++) {
                                jsApiPath.add(arr.get(i).toString());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    channelMerchantAccessAuthQueryContext.setProcessStatus(false);
                    channelMerchantAccessAuthQueryContext.setRemark(e.getMessage());
                }
            }
            merchantWechatConfigListDto.setAppIdList(appIdList);
            merchantWechatConfigListDto.setJsApiPath(jsApiPath);
            channelMerchantAccessAuthQueryContext.setMerchantWechatConfigListDto(merchantWechatConfigListDto);
        } catch (Exception e) {
            log.error("国通微信配置查询请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantAccessAuthQueryContext.setRemark("国通微信配置查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 获取微信授权链接
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<GtzfPayConfig> gtzfPayConfigCommonResult = channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!gtzfPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(gtzfPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            GtzfPayConfig gtzfPayConfig = gtzfPayConfigCommonResult.getData();
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessAuthQueryContext.getMerchantAccessInfo();

            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthList();
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);

            CommonResult<Map<String, String>> authCommonResult = GtzfPayMerchantParamsHandle.wxAuthQuery(gtzfPayConfig, merchantAccessInfo.getSubMchId());
            Map<String, String> authParams = authCommonResult.getData();
            authParams.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(authParams), gtzfPayConfig.getMchPublicKey()));
            String authUrl = domain(channelMerchantAccessAuthQueryContext.isTest()) + GtzfPayConstant.MERCHANT_WX_AUTH_RESULT_QUERY;

            log.info("国通微信报备查询请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.post(authUrl, JsonUtils.toJsonString(authParams));
            log.info("国通微信报备查询返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"000000".equals(authResp.getStr("code"))) {
                channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessAuthQueryContext.setRemark(authResp.getStr("msg"));
                log.error("国通微信报备查询异常 message: {}", authResp.getStr("msg"));
                return;
            }

            JSONObject funcInfo = authResp.getJSONObject("data");
            MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.stream().filter(obj -> StringUtils.hasText(obj.getMchId())).findFirst().orElse(null);
            if (merchantAccessAuthDO == null) {
                return;
            }

            //判断如果有认证链接强制为通过
            if (StringUtils.hasText(funcInfo.getStr("picUrl"))) {
                merchantAccessAuthDO.setAuthUrl(funcInfo.getStr("picUrl"));
                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
            } else {
                switch (funcInfo.getStr("wxAuth")) {
                    case "01":
                    case "08":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                        break;
                    case "02":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                        break;
                    case "03":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_AUTH.getCode());
                        break;
                    case "04":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                        break;
                    case "05":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                    case "06":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN.getCode());
                        break;
                    case "07":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                        break;
                }
                merchantAccessAuthDO.setRejectReason(funcInfo.getStr("wxAuthFail"));
            }

            if (MerchantEnum.MERCHANT_AUTH_STATUS.from(merchantAccessAuthDO.getStatus()) == MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE) {
                CommonResult<Map<String, String>> reqCommonResult = GtzfPayMerchantParamsHandle.wxAuthState(gtzfPayConfig, merchantAccessInfo.getSubMchId(), merchantAccessAuthDO.getSubMchId());
                Map<String, String> reqParams = reqCommonResult.getData();
                reqParams.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(reqParams), gtzfPayConfig.getMchPublicKey()));

                String url = domain(channelMerchantAccessAuthQueryContext.isTest()) + GtzfPayConstant.MERCHANT_WX_AUTH_STATE;
                log.info("国通微信授权查询请求参数:{}", JsonUtils.toJsonString(reqParams));
                String authQueryResponse = HttpUtils.post(url, JsonUtils.toJsonString(reqParams));
                log.info("国通微信授权查询返回参数:{}", authQueryResponse);
                JSONObject authQueryResp = JsonUtils.parseObj(authQueryResponse);
                if (!"000000".equals(authQueryResp.getStr("code"))) {
                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(authQueryResp.getStr("msg"));
                    log.error("国通微信授权查询异常 message: {}", authQueryResp.getStr("msg"));
                    return;
                }
                switch (authQueryResp.getJSONObject("data").getStr("wxAuthState")) {
                    case "1":
                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
                }
                channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
            }
        } catch (Exception e) {
            log.error("国通微信报备查询请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantAccessAuthQueryContext.setRemark("国通微信报备查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processAliAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<GtzfPayConfig> gtzfPayConfigCommonResult = channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!gtzfPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(gtzfPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            GtzfPayConfig gtzfPayConfig = gtzfPayConfigCommonResult.getData();
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessAuthQueryContext.getMerchantAccessInfo();

            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthDbList();
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.FINISH);

            CommonResult<Map<String, String>> authCommonResult = GtzfPayMerchantParamsHandle.aliAuthQuery(gtzfPayConfig, merchantAccessInfo.getSubMchId());
            Map<String, String> authParams = authCommonResult.getData();
            authParams.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(authParams), gtzfPayConfig.getMchPublicKey()));

            String authUrl = domain(channelMerchantAccessAuthQueryContext.isTest()) + GtzfPayConstant.MERCHANT_ALI_AUTH_RESULT_QUERY;
            log.info("国通支付宝报备查询请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.post(authUrl, JsonUtils.toJsonString(authParams));
            log.info("国通支付宝报备查询返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"000000".equals(authResp.getStr("code"))) {
                channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessAuthQueryContext.setRemark(authResp.getStr("msg"));
                log.error("国通支付宝报备查询异常 message: {}", authResp.getStr("msg"));
                return;
            }

            JSONObject funcInfo = authResp.getJSONObject("data");
            MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.stream().filter(obj -> StringUtils.hasText(obj.getMchId())).findFirst().orElse(null);
            if (merchantAccessAuthDO == null) {
                return;
            }

            merchantAccessAuthDO.setAuthUrl(funcInfo.getStr("qrCode"));
            switch (funcInfo.getStr("zfbAuth")) {
                case "01":
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                    break;
                case "02":
                case "03":
                case "08":
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                    break;
                case "04":
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                case "05":
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                    break;
                case "06":
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN.getCode());
                    break;
                case "07":
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                    break;
            }
            merchantAccessAuthDO.setRejectReason(funcInfo.getStr("zxbAuthFail"));

            if (MerchantEnum.MERCHANT_AUTH_STATUS.from(merchantAccessAuthDO.getStatus()) == MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE) {
                CommonResult<Map<String, String>> reqCommonResult = GtzfPayMerchantParamsHandle.wxAuthState(gtzfPayConfig, merchantAccessInfo.getSubMchId(), merchantAccessAuthDO.getSubMchId());
                Map<String, String> reqParams = reqCommonResult.getData();
                reqParams.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(reqParams), gtzfPayConfig.getMchPublicKey()));
                log.info("国通支付宝授权查询请求参数:{}", JsonUtils.toJsonString(reqParams));
                String url = domain(channelMerchantAccessAuthQueryContext.isTest()) + GtzfPayConstant.MERCHANT_ALI_AUTH_STATE;
                String authQueryResponse = HttpUtils.post(url, reqParams);
                log.info("国通支付宝授权查询返回参数:{}", authQueryResponse);
                JSONObject authQueryResp = JsonUtils.parseObj(authQueryResponse);
                if (!"000000".equals(authQueryResp.getStr("code"))) {
                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(authQueryResp.getStr("msg"));
                    log.error("国通支付宝授权查询异常 message: {}", authQueryResp.getStr("msg"));
                    return;
                }
                JSONObject authObj = authQueryResp.getJSONObject("data");
                switch (authObj.getStr("zfbAuthState")) {
                    case "1":
                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
                }
            }
        } catch (Exception e) {
            log.error("国通支付宝报备查询请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantAccessAuthQueryContext.setRemark("国通支付宝报备查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }
}

